package smartvillage.controller;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import smartvillage.mapper.AnswerMapper;
import smartvillage.mapper.HouseholdMapper;
import smartvillage.pojo.Answer;
import smartvillage.pojo.Household;
import smartvillage.result.Result;
import smartvillage.utils.JWTUtil;
import smartvillage.vo.AnswerVO;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/answer")
@CrossOrigin
@Slf4j
public class AnswerController {

    @Autowired
    AnswerMapper answerMapper;

    @Autowired
    HouseholdMapper householdMapper;

    //根据数据调查的id查询旗下所有的回复
    @GetMapping("/questionnaire/{id}")
    public Result<List<AnswerVO>> getAllAnswerByQuestionnaireId(@PathVariable Integer id){
        List<AnswerVO> allAnswerByQuestionnaireId = answerMapper.getAllAnswerByQuestionnaireId(id);
        return Result.success(allAnswerByQuestionnaireId);
    }

    //新增回复
    @PostMapping("/{questionnair}")
    public Result addAnswer(@RequestBody Answer answer, HttpServletRequest request, @PathVariable Integer questionnair){
        //设置当前的日期和时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        answer.setDatetime(formattedDateTime);
        //设置回复者的id
        String token = request.getHeader("token");
        Claims claims = JWTUtil.parseJWT("Rural", token);
        String tele = claims.get("tele").toString();
        Household householdByHolder = householdMapper.getHouseholdByHolder(tele);
        answer.setHousehold(householdByHolder.getId());
        //设置回复的调查
        answer.setQuestionnaire(questionnair);
        answerMapper.addAnswer(answer);
        return Result.success();
    }


}
